# -*- coding: utf-8 -*-
"""
Created on Mon Oct  8 14:32:52 2018

@author: luolei

交叉相关性计算
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import json
import sys

sys.path.append('../')

from lib import *
from lib.data_analysis import *


if __name__ == '__main__':
	#%% 载入数据
	data = pd.read_csv('../../data/runtime/data_nmlzd.csv')
	
	#%% CCF相关性计算
	d_list = np.arange(-1500, 1520, 20)         # **手动设定检测时滞范围
	seg_len = 1000                              # **手动设定单次ccf计算选取的序列长度
	start_locs = np.arange(3000, 17000, 200)  # **手动设置每次检测序列的起始位置

	plt.figure(figsize = [8, 8 * len(target_cols)])
	total_time_delay_ccf = {}
	for col_x in selected_cols:
		total_time_delay_ccf[col_x] = {}
		for col_y in target_cols:
			print('processing col_x: {}, col_y: {}'.format(col_x, col_y))

			# 计算time_delay_ccf结果
			series_a, series_b = np.array(data[col_x]), np.array(data[col_y])
			time_delay_ccf = time_delay_ccf_test(series_a, series_b, d_list, seg_len, start_locs)
			total_time_delay_ccf[col_x][col_y] = time_delay_ccf

			# 计算背景均值和标准差
			bg_values = [abs(v) for k, v in time_delay_ccf.items() if abs(k) > ccf_bg_split_loc]  # **注意CCF值取了绝对值方便比较
			mean, std = np.mean(bg_values), np.std(bg_values)
			sig_thres = mean + 3 * std

			# 画图
			abs_ccf_values = np.abs(list(time_delay_ccf.values()))

			plt.subplot(
				len(selected_cols),
				len(target_cols),
				len(target_cols) * selected_cols.index(col_x) + target_cols.index(col_y) + 1
			)
			plt.plot(time_delay_ccf.keys(), np.abs(abs_ccf_values))  # ** 注意取了绝对值
			plt.fill_between(time_delay_ccf.keys(), abs_ccf_values)
			plt.plot([d_list[0], d_list[-1]], [0, 0], 'k', linewidth = 0.5)
			plt.plot([d_list[0], d_list[-1]], [sig_thres, sig_thres], 'r', linewidth = 0.5)
			plt.plot([0, 0], [-1, 1], 'k', linewidth = 0.8)
			plt.xlim([d_list[0], d_list[-1]])

			max_ccf = max(abs_ccf_values)
			if max_ccf >= 1.0:
				plt.ylim([0.0, max_ccf // 1 + 1])
			elif 0.5 <= max_ccf < 1.0:
				plt.ylim([0.0, 1.0])
			elif 0.3 <= max_ccf < 0.5:
				plt.ylim([0.0, 0.5])
			elif 0.0 <= max_ccf < 0.3:
				plt.ylim([0.0, 0.3])

			plt.xticks(fontsize = 4)
			plt.yticks(fontsize = 4)
			if col_x == selected_cols[0]:
				plt.title(col_y, fontsize = 5)
			plt.legend([col_x], loc = 'lower right', fontsize = 5)

			plt.tight_layout()
			plt.show()
			plt.pause(0.5)

	#%% 保存计算结果
	plt.savefig('../../graph/ccf_analysis_fig.png', dpi = 600)
	with open('../../data/runtime/ccf_time_delay_correlation_results.json', 'w') as f:
		json.dump(total_time_delay_ccf, f)


